import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { useAsyncRoutes } from './store/modules/asyncRoutes';
import router from '@/router';
import { RouteLocationNormalized } from 'vue-router';
import { whiteList } from '_c/constant';
import { isLogin } from '@/utils';
import { notFound } from './router/index';
NProgress.configure({ showSpinner: false });
router.beforeEach(async (to: RouteLocationNormalized, _: RouteLocationNormalized, next: any) => {
    NProgress.start();

    const asyncStore = useAsyncRoutes();
    if (isLogin()) {
        // 已登录
        if (to.path == '/login') {
            next();
            NProgress.done();
        } else {
            if (asyncStore.addRoutes.length == 0) {
                // 保证404处于最后
                const isExistent = router.hasRoute('noFound');
                isExistent ? router.removeRoute('notFound') : '';
                try {
                    // 请求路由权限
                    await asyncStore.setRoleRoutes();
                    asyncStore.addRoutes.forEach((route: any) => {
                        router.addRoute(route);
                    });
                    // 将404添加进去
                    //现在才添加的原因是：作为一级路由，当刷新，动态路由还未加载，路由就已经做了匹配，找不到就跳到了404
                    !isExistent ? router.addRoute(notFound) : '';
                    // Set the replace: true, so the navigation will not leave a history record
                    next({ ...to, replace: true });
                } catch (err) {
                    // Other pages that do not have permission to access are redirected to the login page.
                    next({ path: '/login', query: { redirect: to.path, ...to.query } });
                    NProgress.done();
                }
            } else {
                next();
            }
        }
    } else {
        // 无 token 未登录状态
        if (whiteList.indexOf(to.path) !== -1) {
            // In the free login whitelist, go directly
            next();
        } else {
            // Other pages that do not have permission to access are redirected to the login page.
            next({ path: '/login', query: { redirect: to.path, ...to.query } });
            NProgress.done();
        }
    }
});

router.afterEach((to: RouteLocationNormalized) => {
    // console.log(to);
    NProgress.done();
});
